<template>
	<div class="app-container">
		<el-form
			:model="queryParams"
			ref="queryRef"
			:inline="true"
			v-show="showSearch"
			label-width="68px"
		>
			<el-form-item label="项目ID" prop="surveyId">
				<el-input
					v-model="queryParams.surveyId"
					placeholder="请输入项目ID"
					clearable
					@keyup.enter="handleQuery"
				/>
			</el-form-item>
			<el-form-item label="项目名称" prop="surveyTitle">
				<el-input
					v-model="queryParams.surveyTitle"
					placeholder="请输入项目名称"
					clearable
					@keyup.enter="handleQuery"
				/>
			</el-form-item>
			<el-form-item label="语言/国家" prop="surveyLanguage" label-width="80px">
				<el-input
					v-model="queryParams.surveyLanguage"
					placeholder="请输入调查语言/国家"
					clearable
					@keyup.enter="handleQuery"
				/>
			</el-form-item>
			<el-form-item label="公司" prop="companyId">
				<el-select
					v-model="queryParams.companyId"
					placeholder="选择公司"
					style="width: 240px"
				>
					<el-option
						v-for="item in companyList"
						:key="item.id"
						:label="item.companyName"
						:value="item.id"
					/>
				</el-select>
			</el-form-item>

			<el-form-item label="调查时间" prop="surveyTime">
				<el-date-picker
					clearable
					v-model="queryParams.surveyTime"
					type="date"
					value-format="YYYY-MM-DD"
					placeholder="请选择调查时间"
				>
				</el-date-picker>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
				<el-button icon="Refresh" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button
					type="primary"
					plain
					icon="Plus"
					@click="handleAdd"
					v-hasPermi="['survey:surveyList:add']"
					>新增</el-button
				>
			</el-col>
			<el-col :span="1.5">
				<el-button
					type="success"
					plain
					icon="Edit"
					:disabled="single"
					@click="handleUpdate"
					v-hasPermi="['survey:surveyList:edit']"
					>修改</el-button
				>
			</el-col>
			<el-col :span="1.5">
				<el-button
					type="success"
					plain
					icon="Edit"
					:disabled="single"
					@click="Modifyremarks"
					v-hasPermi="['survey:surveyList:edit']"
					>修改备注</el-button
				>
			</el-col>
			<el-col :span="1.5">
				<el-button
					type="warning"
					plain
					icon="stopwatch"
					:disabled="multiple"
					@click="updateReady"
					v-hasPermi="['survey:surveyList:export']"
					color="orange"
					>暂停/开始</el-button
				>
			</el-col>
			<el-col :span="1.5">
				<el-button
					type="danger"
					plain
					icon="Delete"
					:disabled="multiple"
					@click="handleBatchDelete"
					v-hasPermi="['survey:surveyList:remove']"
					>删除</el-button
				>
			</el-col>
			<el-col :span="1.5">
				<el-button
					type="info"
					plain
					icon="Upload"
					@click="handleImport"
					v-hasPermi="['system:surveyList:import']"
					>导入</el-button
				>
			</el-col>
			<right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<ul v-infinite-scroll="load" class="infinite-list" style="overflow: auto">
			<el-table
				v-loading="loading"
				:data="surveyListList"
				@selection-change="handleSelectionChange"
				:default-sort="defaultSort"
				@sort-change="handleSortChange"
				border
			>
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="标识ID" align="center" prop="id" />
				<el-table-column label="项目ID" align="center" prop="surveyId" />
				<el-table-column label="项目名称" align="center" prop="surveyTitle" />
				<el-table-column label="公司名称" align="center" prop="companyName" />
				<el-table-column label="IR/当前" align="center" prop="surveyIr" />
				<el-table-column label="Loi" align="center" prop="surveyLoi" />
				<el-table-column label="配额" align="center" prop="surveyQuota" />
				<el-table-column
					label="价格"
					align="center"
					prop="surveyPrice"
					sortable="custom"
					:sort-orders="['descending', 'ascending']"
				/>
				<el-table-column label="调查语言/国家" align="center" prop="surveyLanguage" />
				<el-table-column label="点击/完成/配额" align="center" prop="surveyQuotaCount">
					<template #default="scope">
						<span v-html="getFormattedQuotaCount(scope.row.surveyQuotaCount)"></span>
					</template>
				</el-table-column>
				<el-table-column
					label="更新时间"
					align="center"
					prop="surveyTime"
					width="180"
					sortable="custom"
					:sort-orders="['descending', 'ascending']"
				>
					<template #default="scope">
						<span>{{ parseTime(scope.row.surveyTime) }}</span>
					</template>
				</el-table-column>
				<el-table-column label="调查备注" align="center" prop="surveyRemark" />
				<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
					<template #default="scope">
						<el-button-group class="ml-4">
							<el-button
								v-if="scope.row.surveyReady === 0"
								type="danger"
								plain
								disabled
								:icon="Edit"
								@click="handgeturl(scope.row)"
								title="答题链接"
							/>
							<el-button
								v-if="scope.row.surveyReady === 1"
								el-button
								type="primary"
								:icon="Edit"
								@click="handgeturl(scope.row)"
								title="答题链接"
							/>
							<el-button
								type="primary"
								:icon="Brush"
								@click="getstrategy(scope.row)"
								title="攻略"
							/>
						</el-button-group>
					</template>
				</el-table-column>
			</el-table>
		</ul>
		<pagination
			v-show="total > 0"
			:total="total"
			v-model:page="queryParams.pageNum"
			v-model:limit="queryParams.pageSize"
			@pagination="getList"
		/>

		<!--    <el-drawer-->
		<!--        v-model="drawer"-->
		<!--        title="I am the title"-->
		<!--        :direction="direction"-->
		<!--        :before-close="handleClose"-->
		<!--    >-->
		<!--      <span>Hi, there!</span>-->
		<!--    </el-drawer>-->
		<el-drawer
			v-model="drawer"
			title="调查攻略"
			:direction="direction"
			:before-close="handleClose"
			size="80%"
		>
			<div v-if="forms && forms.specs">
				<p v-if="forms.specs.surveyText" v-html="forms.specs.surveyText"></p>
				<p v-else>暂无攻略</p>
			</div>
			<span v-else>加载中...</span>
		</el-drawer>

		<!-- 添加或修改调查列表对话框 -->
		<el-dialog
			:title="title"
			v-model="open"
			:style="{ minWidth: '600px', minHeight: '80vh' }"
			append-to-body
			:close-on-click-modal="false"
		>
			<el-form
				ref="surveyListRef"
				:model="form"
				:rules="rules"
				label-width="80px"
				style="max-height: 70vh; overflow-y: auto"
			>
				<el-form-item label="项目ID" prop="surveyId">
					<el-input v-model="form.surveyId" placeholder="请输入项目ID" onkeyup="this.value=this.value.replace(/[, ]/g,'')"/>
				</el-form-item>
				<el-form-item label="项目名称" prop="surveyTitle">
					<el-input v-model="form.surveyTitle" placeholder="请输入项目名称" onkeyup="this.value=this.value.replace(/[, ]/g,'')" />
				</el-form-item>
				<el-form-item label="公司" prop="companyId">
					<el-select
						v-model="form.companyId"
						placeholder="选择公司"
						:style="{ width: '100%' }"
					>
						<el-option
							v-for="item in companyList"
							:key="item.id"
							:label="item.companyName"
							:value="item.id"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="IR" prop="surveyIr">
					<el-input v-model="form.surveyIr" placeholder="请输入IR" onkeyup="this.value=this.value.replace(/[, ]/g,'')"/>
				</el-form-item>
				<el-form-item label="LOi" prop="surveyLoi">
					<el-input v-model="form.surveyLoi" placeholder="请输入LOi" onkeyup="this.value=this.value.replace(/[, ]/g,'')" />
				</el-form-item>
				<el-form-item label="配额" prop="surveyQuota">
					<el-input v-model="form.surveyQuota" placeholder="请输入配额" onkeyup="this.value=this.value.replace(/[, ]/g,'')" />
				</el-form-item>
				<el-form-item label="价格" prop="surveyPrice">
					<el-input v-model="form.surveyPrice" placeholder="请输入价格" onkeyup="this.value=this.value.replace(/[, ]/g,'')"/>
				</el-form-item>
				<el-form-item label="调查国家" prop="surveyLanguage">
					<el-input v-model="form.surveyLanguage" placeholder="请输入调查国家" onkeyup="this.value=this.value.replace(/[, ]/g,'')" />
				</el-form-item>
				<el-form-item label="调查网址" prop="surveyUrl">
					<el-input v-model="form.surveyUrl" placeholder="请输入调查网址" onkeyup="this.value=this.value.replace(/[, ]/g,'')" />
				</el-form-item>
			</el-form>
			<div class="about" style="max-height: 30vh; overflow-y: auto">
				<!-- <editor api-key="zfio7hxnh1xtaeajzadnbz5xssfi5d49a7peqf05f2zjtpm8" :init="init" v-model="editorContent">

        </editor> -->
				<editor
					:height="`${500}px`"
					ref="editorRef"
					@update:getHtml="getHtml"
					:getHtml="editorContent"
				></editor>
			</div>

			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitForm">确 定</el-button>
					<el-button @click="cancel">取 消</el-button>
				</div>
			</template>
		</el-dialog>
		<!-- 添加或修改调查列表对话框 -->
		<el-dialog
			:title="updateremarks"
			v-model="updateremarksopen"
			:style="{ minWidth: '600px', minHeight: '80vh' }"
			append-to-body
		>
			<el-form
				ref="surveyListRef"
				:model="form2"
				:rules="rules"
				label-width="80px"
				style="max-height: 70vh; overflow-y: auto"
			>
				<el-form-item label="项目ID" prop="surveyId">
					<el-input v-model="form2.surveyId" placeholder="请输入项目ID" />
				</el-form-item>
				<el-form-item label="项目名称" prop="surveyTitle">
					<el-input v-model="form2.surveyTitle" placeholder="请输入项目名称" />
				</el-form-item>
				<el-form-item label="IR" prop="surveyIr">
					<el-input v-model="form2.surveyIr" placeholder="请输入IR" />
				</el-form-item>
				<el-form-item label="LOi" prop="surveyLoi">
					<el-input v-model="form2.surveyLoi" placeholder="请输入LOi" />
				</el-form-item>
				<el-form-item label="配额" prop="surveyQuota">
					<el-input v-model="form2.surveyQuota" placeholder="请输入配额" />
				</el-form-item>
				<el-form-item label="价格" prop="surveyPrice">
					<el-input v-model="form2.surveyPrice" placeholder="请输入价格" />
				</el-form-item>
				<el-form-item label="调查国家" prop="surveyLanguage">
					<el-input v-model="form2.surveyLanguage" placeholder="请输入调查国家" />
				</el-form-item>
				<el-form-item label="调查网址" prop="surveyUrl">
					<el-input v-model="form2.surveyUrl" placeholder="请输入调查网址" />
				</el-form-item>
				<el-form-item label="调查备注" prop="surveyRemark">
					<el-input v-model="form2.surveyRemark" placeholder="请输入调查备注" />
				</el-form-item>
			</el-form>

			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitForm1">确 定</el-button>
					<el-button @click="cancel">取 消</el-button>
				</div>
			</template>
		</el-dialog>

		<!-- 用户导入对话框 -->
		<el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
			<el-upload
				ref="uploadRef"
				:limit="1"
				accept=".xlsx, .xls"
				:headers="upload.headers"
				:action="upload.url + '?updateSupport=' + upload.updateSupport"
				:disabled="upload.isUploading"
				:on-progress="handleFileUploadProgress"
				:on-success="handleFileSuccess"
				:auto-upload="false"
				drag
			>
				<el-icon class="el-icon--upload"><upload-filled /></el-icon>
				<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>

				<template #tip>
					<div class="el-upload__tip text-center">
						<div class="el-upload__tip">
							<el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
						</div>
						<span>仅允许导入xls、xlsx格式文件。</span>
						<el-link
							type="primary"
							:underline="false"
							style="font-size: 12px; vertical-align: baseline"
							@click="importTemplate"
							>下载模板</el-link
						>
					</div>
				</template>
			</el-upload>

			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitFileForm">确 定</el-button>
					<el-button @click="upload.open = false">取 消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<style>
/* 在el-dialog中tinymce z-index 被太小而被遮挡时要加这两句 */
.tox-tinymce-aux {
  z-index: 99999 !important;
}

.tinymce.ui.FloatPanel {
  z-index: 99;
}

.infinite-list {
  height: 800px;
  padding: 0;
  margin: 0;
  list-style: none;
}

.infinite-list .infinite-list-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  background: var(--el-color-primary-light-9);
  margin: 10px;
  color: var(--el-color-primary);
}

.infinite-list .infinite-list-item+.list-item {
  margin-top: 10px;
}
</style>

<script setup name="SurveyList">
// 富文本
// import Editor from '@tinymce/tinymce-vue';
import editor from "@/components/editor1/index.vue";
const forms = ref({}); // 使用 ref 创建响应式引用

// 表单重置
function resets() {
  form.value = {}; // 使用 .value 访问和设置响应式引用
  // 可以在这里添加更多的重置逻辑
}

function getstrategy(row) {
  resets(); // 直接调用 reset，无需使用 this
  const _id = row.surveyTitle;
  getSurveystrategyBySurveyTitle(_id).then((response) => {
    forms.value = {
      // 使用 .value 访问和设置响应式引用
      specs: response.data,
    };
    drawer.value = true; // 使用 .value 访问和设置响应式引用
  });
}

const init = {
  // language_url: './public/tinymce/zh_CN.js', //引入语言包文件
  language: "zh_CN", //语言类型
  plugins:
    "print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount textpattern autosave",
  toolbar:
    "fullscreen undo redo restoredraft  | forecolor backcolor bold italic underline fontselect fontsizeselect  | formatselect  |\
				alignleft aligncenter alignright alignjustify outdent indent | bullist numlist | table cut copy paste pastetext| blockquote subscript superscript removeformat  | code selectall | indent2em lineheight formatpainter axupimgs |\
                 image media charmap emoticons hr pagebreak insertdatetime print preview ",
  fontsize_formats:
    "12px 14px 16px 18px 20px 22px 24px 28px 32px 36px 48px 56px 72px", //字体大小
  font_formats:
    "微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;",
  menu: {
    //顶部菜单管理
    edit: {
      title: "编辑",
      items: "undo redo | cut copy paste pastetext | selectall",
    },
    insert: { title: "插入", items: "link image  |  hr" },
    view: { title: "查看", items: "visualaid" },
  },
  branding: false,
  images_upload_handler: (blobInfo, success, failure) => {
    const img = "data:image/jpeg;base64," + blobInfo.base64();
    success(img);
  },
};

import { Edit, Brush } from "@element-plus/icons-vue";
import {
  listSurveyList,
  getSurveyList,
  addSurveyList,
  updateSurveyList,
  getSurveyUrl,
  delSurveyList,
  updateSurveyReady,
  getSurveyModifyremarks,
  updateremarkssurveyList,
} from "@/api/survey/surveyList";
import { allListCompany } from "@/api/company/company";
import { getUserProfile } from "@/api/system/user.js";
/*** 调查列表导入参数 */
const upload = reactive({
  // 是否显示弹出层（调查列表导入）
  open: false,
  // 弹出层标题（调查列表导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的调查列表数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/survey/surveyList/importData",
});

const { proxy } = getCurrentInstance();

const surveyListList = ref([]);
const open = ref(false);
const updateremarksopen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const updateremarks = ref("");
const editorContent = ref("");
const companyList = ref([]);
const data = reactive({
  form: {},
  form2: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    surveyAddId: null,
    surveyId: null,
    surveyTitle: null,
    surveyIr: null,
    surveyLoi: null,
    surveyQuota: null,
    surveyPrice: null,
    surveyLanguage: null,
    surveyUrl: null,
    surveyTime: null,
    surveyReady: null,
    surveyText: null,
    surveyStrategy: null,
    surveyQuotaCount: null,
    surveyRemark: null,
    companyId:null
  },
  rules: {
    surveyTitle: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
    surveyId: [{ required: true, message: "项目ID不能为空", trigger: "blur" }],
    companyId: [{ required: true, message: "公司不能为空", trigger: "blur" }],
    surveyIr: [{ required: true, message: "IR不能为空", trigger: "blur" }],
    surveyLoi: [{ required: true, message: "LOi不能为空", trigger: "blur" }],
    surveyQuota: [{ required: true, message: "配额不能为空", trigger: "blur" }],
    surveyPrice: [{ required: true, message: "价格不能为空", trigger: "blur" }],
    surveyLanguage: [{ required: true, message: "调查国家不能为空", trigger: "blur" }],
    surveyUrl: [{ required: true, message: "调查网址不能为空", trigger: "blur" }]
   },
});

const { queryParams, form, form2, rules } = toRefs(data);

function getFormattedQuotaCount(surveyQuotaCount) {
  const counts = surveyQuotaCount.split(" / ");
  let formattedCounts = "";
  ``;
  for (let i = 0; i < counts.length; i++) {
    formattedCounts += `<span style="color: ${getStatusColor(i)}">${counts[i]
      }</span>`;
    if (i !== counts.length - 1) {
      formattedCounts += " / "; // 添加斜杠分隔符
    }
  }
  return formattedCounts;
}

function getStatusColor(index) {
  if (index === 0) {
    1;
    return "blue"; // 设置第一个数字为蓝色
  } else if (index === 1) {
    return "green"; // 设置第二个数字为绿色
  } else {
    return "red"; // 设置其他数字为红色
  }
}

/** 查询调查列表列表 */
function getList() {
  loading.value = true;
  listSurveyList(queryParams.value).then((response) => {
    surveyListList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  updateremarksopen.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    surveyAddId: null,
    surveyId: null,
    surveyTitle: null,
    surveyIr: null,
    surveyLoi: null,
    surveyQuota: null,
    surveyPrice: null,
    surveyLanguage: null,
    surveyUrl: null,
    surveyTime: null,
    surveyReady: null,
    surveyText: null,
    surveyStrategy: null,
    editorContent: null,
    surveyQuotaCount: null,
    surveyRemark: null,
    companyId:null
  };
  form2.value = {
    id: null,
    surveyAddId: null,
    surveyId: null,
    surveyTitle: null,
    surveyIr: null,
    surveyLoi: null,
    surveyQuota: null,
    surveyPrice: null,
    surveyLanguage: null,
    surveyUrl: null,
    surveyTime: null,
    surveyReady: null,
    surveyStrategy: null,
    editorContent: null,
    surveyQuotaCount: null,
    surveyRemark: null,
  };
  proxy.resetForm("surveyListRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => ({
    id: item.id,
    surveyReady: item.surveyReady,
    surveyId: item.surveyId,
    surveyTitle: item.surveyTitle,
  }));
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
let editorRef = ref(null);
/** 新增按钮操作 */
function handleAdd() {
  reset();
  editorContent.value = "";
  editorRef?.value?.clearEditorContent();
  open.value = true;
  title.value = "添加调查列表";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value[0].id;
  getSurveyList(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改调查列表";
    // 假设response.data中包含了surveyUrl，我们可以这样将它设置到富文本编辑器中：
    if (response.data.surveyStrategy) {
      // 假设富文本编辑器绑定的数据是editorContent
      editorContent.value = response.data.surveyStrategy;
      console.log(editorContent.value);
    }
  });
}

/** 修改备注按钮操作 */
function Modifyremarks(row) {
  reset();
  const _id = row.id || ids.value[0].id;
  getSurveyModifyremarks(_id).then((response) => {
    form2.value = response.data;
    updateremarksopen.value = true;
    updateremarks.value = "修改调查备注";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["surveyListRef"].validate((valid) => {
    if (valid) {
      // 获取富文本编辑器当前的内容
      const editor = editorContent.value; // 或者其他方式获取，取决于你的富文本编辑器如何绑定数据
      if (form.value.id != null) {
        // 将富文本编辑器的内容写入form.value的相应属性中
        form.value.surveyStrategy = editor;
        updateSurveyList(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        // 将富文本编辑器的内容写入form.value的相应属性中
        form.value.surveyStrategy = editor;
        addSurveyList(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 提交按钮 */
function submitForm1() {
  proxy.$refs["surveyListRef"].validate((valid) => {
    if (form2.value.id != null) {
      updateremarkssurveyList(form2.value).then((response) => {
        proxy.$modal.msgSuccess("修改成功");
        updateremarksopen.value = false;
        getList();
      });
    }
  });
}

const state = reactive({
  user: {},
  roleGroup: {},
  postGroup: {},
});

function getUser() {
  getUserProfile().then((response) => {
    state.user = response.data;
    state.roleGroup = response.roleGroup;
    state.postGroup = response.postGroup;
  });
}

function handleBatchDelete() {
  const _ids = ids.value.map((item) => item.id).join(", "); // 获取所有选中项的id并用逗号分隔
  if (!_ids) {
    // 如果没有选中项，则给出提示并返回
    proxy.$modal.msgWarning("请选择要删除的项");
    return;
  }

  proxy.$modal
    .confirm("是否确认删除选中的调查记录？")
    .then(function () {
      return delSurveyList(_ids); // 批量删除操作
    })
    .then(() => {
      getList(); // 删除成功后刷新列表
      proxy.$modal.msgSuccess("批量删除成功");
    })
    .catch(() => {
      // 处理删除失败情况
      proxy.$modal.msgError("批量删除失败");
    });
}

/** 获取答题链接按钮 */
import axios from "axios"; // 导入axios库
// 定义一个变量来跟踪按钮状态，默认为可点击状态
let isButtonDisabled = false;
async function handgeturl(row) {
  if (isButtonDisabled) {
      return;
    }
    isButtonDisabled = true;
    getUser();
    // 使用async/await异步获取IP地址
    let ipResponse = null;
    try{
      ipResponse = await axios.get("http://api.ipify.org?format=json");
    }catch(error){
      console.log(ipResponse,"ipResponse")
    }
    let ipAddress = null;
    if (!ipResponse) {
        ipAddress = '127.0.0.1';
    }else{
       ipAddress = ipResponse.data.ip;
    }
    // 获取要删除的项的ID
    const _ids = row.surveyTitle || ids.value; // 假设ids.value已经在组件的响应式数据中定义
    // 调用getSurveyUrl函数，传入_ids和ipAddress
    const response = await getSurveyUrl(_ids, ipAddress, state.user.userName);
    const surveyUrl = response.data; // Assuming the URL is returned in the 'data' field

    if(surveyUrl){
      // 将URL复制到剪切板
      copyToClipboard(surveyUrl);
        // 显示成功消息
        proxy.$message({
        message: "获取成功！",
        type: "success",
      });
    }else{
      // 错误处理
      proxy.$message({
        message: "获取失败或项目暂停！",
        type: "error",
      });
    }
  isButtonDisabled = false;
  getList();
}

function copyToClipboard(text) {
  var textarea = document.createElement("textarea");
  textarea.value = text;
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand("copy");
  document.body.removeChild(textarea);
}

/** 排序触发事件 */
const defaultSort = ref({ prop: "surveyStartTime", order: "descending" });
function handleSortChange(column, prop, order) {
  queryParams.value.orderByColumn = column.prop;
  queryParams.value.isAsc = column.order;
  getList();
}

/** 查询公司下拉列表 */
function getCompanyList() {
  allListCompany().then(response => {
    console.log(response, "response")
    companyList.value = response.rows;
  });
}
getCompanyList();
getList();

/*关闭右侧弹窗攻略*/
import { ref } from "vue";
import { ElMessageBox } from "element-plus";
import { delSurveyLog } from "@/api/survey/surveyLog.js";
const drawer = ref(false);
const handleClose = (done) => {
  if (typeof done === "function") {
    ElMessageBox.confirm("你确定要关闭攻略吗?")
      .then(() => {
        done();
      })
      .catch(() => {
        // catch error
      });
  } else {
    console.error("Invalid argument: done must be a function");
  }
};

/*调查攻略查询*/
import { getSurveystrategyBySurveyTitle } from "@/api/survey/surveystrategy";
import { getToken } from "@/utils/auth.js";

/** 暂停开始功能按钮 */
function updateReady() {
  const selectedItems = ids.value; // 获取整个 ids 数组
  // 遍历选中项数组
  selectedItems.forEach((item) => {
    const surveyReady = item.surveyReady;
    const surveyTitle = item.surveyTitle;
    // 调用更新方法
    updateSurveyReady(surveyTitle, surveyReady);
  });
  // 更新完毕后刷新列表
  getList();
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "调查导入";
  upload.open = true;
}
/** 下载模板操作 */
function importTemplate() {
  proxy.download(
    "survey/surveyList/importTemplate",
    {},
    `surveylist_template_${new Date().getTime()}.xlsx`
  );
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
    response.msg +
    "</div>",
    "导入结果",
    { dangerouslyUseHTMLString: true }
  );
  getList();
};
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}

/**
 * 获取富文本中的html
 */
const getHtml = (val) => {
  editorContent.value = val;
};
</script>
